package cn.wolfcode.service.impl;

import cn.wolfcode.domain.Employee;
import cn.wolfcode.domain.Permission;
import cn.wolfcode.exception.LogicException;
import cn.wolfcode.mapper.EmployeeMapper;
import cn.wolfcode.result.QueryObject;
import cn.wolfcode.service.IEmployeeService;
import cn.wolfcode.util.UserContext;
import com.alibaba.druid.support.spring.stat.SpringStatUtils;
import com.github.pagehelper.PageHelper;
import com.github.pagehelper.PageInfo;
import org.apache.ibatis.executor.ExecutorException;
import org.apache.poi.hssf.usermodel.HSSFWorkbook;
import org.apache.poi.ss.usermodel.*;
import org.apache.shiro.crypto.hash.Md5Hash;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;
import org.springframework.util.StringUtils;
import org.springframework.web.context.request.RequestContextHolder;
import org.springframework.web.context.request.ServletRequestAttributes;
import org.springframework.web.multipart.MultipartFile;

import java.io.IOException;
import java.util.Collections;
import java.util.List;

/**
 * @Description:
 * @Author: 伍家钰
 * @Date: 2020/7/10 21:07
 * @Version: 1.0
 */
@Service
public class EmployeeServiceImpl implements IEmployeeService {
    @Autowired
    private EmployeeMapper employeeMapper;


    @Override
    public void delete(Long id) {
        employeeMapper.deleteByPrimaryKey(id);
    }

    @Override
    public void save(Employee employee, Long[] ids) {
        // 对密码进行加密,把用户名当做盐
        Md5Hash md5Hash = new Md5Hash(employee.getPassword(), employee.getName(), 3);
        // 将加密后的密码设置给用户
        employee.setPassword(md5Hash.toString());
        // 1.必须在中间表中添加数据之前保存对象,否则id为空,报空指针异常
        employeeMapper.insert(employee);
        // 2.保存时对象的同时,往中间表中添加数据
        if (ids != null && ids.length > 0) {
            for (Long roleId : ids) {
                employeeMapper.insertRelation(employee.getId(), roleId);
            }
        }
    }

    @Override
    public Employee selectById(Long id) {
        Employee employee = employeeMapper.selectByPrimaryKey(id);
        return employee;
    }

    @Override
    public List<Employee> selectAll() {
        List<Employee> employees = employeeMapper.selectAll();
        return employees;
    }

    @Override
    public void update(Employee employee, Long[] ids) {
        employeeMapper.updateByPrimaryKey(employee);
        // 1.修改员工表时,先删除中间表中对象
        employeeMapper.deleteRelation(employee.getId());
        // 2.修改员工表的数据并将对应的角色信息保存到中间表中
        if (ids != null && ids.length > 0) {
            for (Long roleId : ids) {
                employeeMapper.insertRelation(employee.getId(), roleId);
            }
        }
    }

    @Override
    public PageInfo<Employee> query(QueryObject qo) {
        // 开始分页,插入当前页和每页显示的数据
        PageHelper.startPage(qo.getCurrentPage(), qo.getPageSize());
        //查询数据总数
        List<Employee> employees = employeeMapper.selectForList(qo);
        return new PageInfo<Employee>(employees);
    }

    @Override
    public Employee login(String username, String password) {
        if (!StringUtils.hasText(username)) {
            throw new LogicException("账号不能为空");
        }
        if (!StringUtils.hasText(password)) {
            throw new LogicException("密码不能为空");
        }
        Employee employee = employeeMapper.loginByUsernameAndPassword(username, password);
        if (employee == null) {
            throw new LogicException("账号或者密码错误");
        }
        return employee;
    }

    /**
     * 修改登入密码
     *
     * @param id
     * @param newPassword
     */
    @Override
    public void updateForPassword(Long id, String newPassword) {
        employeeMapper.updateForPassword(id, newPassword);
    }

    @Override
    public void resetPassword(String newPassword, Long id) {
        employeeMapper.updateForPassword(id, newPassword);
    }

    @Override
    public void batchDelete(Long[] ids) {
        employeeMapper.batchDelete(ids);
    }

    @Override
    public Employee selectByName(String name) {
        Employee employee = employeeMapper.selectByName(name);
        return employee;
    }

    @Override
    public Workbook exportXls() {
        // 查询员工数据
        List<Employee> employees = employeeMapper.selectAll();

        // 创建exclect文件
        Workbook wb = new HSSFWorkbook();
        // 创建表
        Sheet sheet = wb.createSheet("员工通讯录");
        // 标题行
        Row row = sheet.createRow(0);
        // 设置内容到单元格中
        row.createCell(0).setCellValue("姓名");
        row.createCell(1).setCellValue("邮箱");
        row.createCell(2).setCellValue("年龄");

        for (int i = 0; i < employees.size(); i++) {
            Employee employee = employees.get(i);
            // 每个员工就是一行
            Row row1 = sheet.createRow(i + 1);
            // 如果用户名和邮箱有一个为空就不在读取了
            if (row1.getCell(0) == null || row1.getCell(1) == null) {
                break;
            }
            //设置内容到单元格中
            employee.setName(row1.getCell(0).getStringCellValue());
            employee.setEmail(row1.getCell(1).getStringCellValue());
            Cell cell = row1.getCell(2);
            // 判断单元格格式
            if (cell.getCellType() == CellType.NUMERIC) {
                employee.setAge((int) row1.getCell(2).getNumericCellValue());
            } else {
                //传入的是String类型的
                employee.setAge(Integer.valueOf(row1.getCell(2).getStringCellValue()));
            }
            employeeMapper.insert(employee);
        }
        return wb;
    }

    @Override
    public void status(Long id, boolean status) {
        employeeMapper.status(id, status);
    }

    @Override
    public void importXls(MultipartFile file) throws IOException {
        // 把接受到的文件以Excel的方式去读取
        Workbook wb = new HSSFWorkbook(file.getInputStream());
        // 读取第一张表
        Sheet sheet = wb.getSheetAt(0);
        // 获取最后一列索引
        int lastRowNum = sheet.getLastRowNum();
        Employee employee = new Employee();
        // 遍历表中的所有列
        for (int i = 1; i <= lastRowNum; i++) {
            // 获取行数据
            Row row = sheet.getRow(i);
            // 将每一列的值设置进对象中
            employee.setName(row.getCell(0).getStringCellValue());
            employee.setEmail(row.getCell(1).getStringCellValue());
            employee.setAge((int) row.getCell(2).getNumericCellValue());
            employeeMapper.insert(employee);
        }
    }

    @Override
    public List<Employee> selectBySn(String... sn) {
        List<Employee> employees = employeeMapper.selectBysn(sn);
        return employees;
    }
}
